import { Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BaseService } from '../../../common/base.service';
import { RoleEntity } from '../entity/role';
import { BaseError as R } from '../../../common/base.error'

@Provide()
export class RoleService extends BaseService<RoleEntity> {
  @InjectEntityModel(RoleEntity)
  roleModel: Repository<RoleEntity>;

  getModel(): Repository<RoleEntity> {
    return this.roleModel;
  }

  async create(entity: RoleEntity) {
    const roleCode = entity.code;
    const isCode = await this.getModel().find({ where: {
      code: roleCode
    }})

    if (isCode.length) {
      throw R.validateError('该角色已存在！')
    }
    return await this.getModel().save(entity);
  }
}